package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.*;
import cn.edu.tju.elm.repository.VirtualWalletRepository;
import cn.edu.tju.elm.repository.VirtualWalletTransactionRepository;
import cn.edu.tju.elm.repository.WalletRuleRepository;
import cn.edu.tju.core.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 虚拟钱包服务实现类
 * 采用DDD充血模型：Domain对象（VirtualWallet）包含业务逻辑，Service层负责协调和事务管理
 */
@Service
@Transactional
public class VirtualWalletServiceImpl implements VirtualWalletService {

    private static final Logger logger = LoggerFactory.getLogger(VirtualWalletServiceImpl.class);

    @Autowired
    private VirtualWalletRepository virtualWalletRepository;
    
    @Autowired
    private VirtualWalletTransactionRepository transactionRepository;
    
    @Autowired
    private WalletRuleRepository walletRuleRepository;

    // ==================== 基础查询方法 ====================

    @Override
    public Optional<VirtualWallet> getVirtualWallet(Long walletId) {
        return virtualWalletRepository.findById(walletId);
    }

    @Override
    public Optional<VirtualWallet> getVirtualWalletByUser(User user) {
        return virtualWalletRepository.findByUser(user);
    }

    @Override
    public Optional<VirtualWallet> getVirtualWalletByUserId(Long userId) {
        return virtualWalletRepository.findByUserId(userId);
    }

    @Override
    public BigDecimal getBalance(Long walletId) {
        Optional<VirtualWallet> wallet = virtualWalletRepository.findById(walletId);
        return wallet.map(VirtualWallet::getCurrentBalance).orElse(BigDecimal.ZERO);
    }

    @Override
    public VirtualWallet createVirtualWallet(User user) {
        // 检查是否已存在钱包
        if (virtualWalletRepository.existsByUserId(user.getId())) {
            throw new IllegalArgumentException("用户已有虚拟钱包");
        }
        
        VirtualWallet wallet = new VirtualWallet(user);
        return virtualWalletRepository.save(wallet);
    }

    // ==================== 充值和提现 ====================

    @Override
    public VirtualWalletTransaction recharge(Long walletId, BigDecimal amount, String remark) {
        try {
            // 1. 获取钱包
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            // 2. 计算充值返点
            BigDecimal bonus = calculateRechargeBonus(amount);
            
            // 3. 记录充值前余额
            BigDecimal balanceBefore = wallet.getBalance();

            // 4. 调用Domain对象的充值方法（充血模型）
            wallet.recharge(amount, bonus);

            // 5. 保存钱包状态
            virtualWalletRepository.save(wallet);

            // 6. 记录充值交易流水
            VirtualWalletTransaction rechargeTransaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.RECHARGE)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .bonusOrFee(BigDecimal.ZERO)
                .description("充值")
                .remark(remark)
                .build();
            transactionRepository.save(rechargeTransaction);

            // 7. 如果有返点，记录返点交易
            if (bonus.compareTo(BigDecimal.ZERO) > 0) {
                VirtualWalletTransaction bonusTransaction = new VirtualWalletTransaction.Builder()
                    .walletId(walletId)
                    .amount(bonus)
                    .transactionType(TransactionType.RECHARGE_BONUS)
                    .balanceBefore(balanceBefore.add(amount))
                    .balanceAfter(wallet.getBalance())
                    .bonusOrFee(bonus)
                    .description("充值返点")
                    .remark("充值" + amount + "元，返点" + bonus + "元")
                    .build();
                transactionRepository.save(bonusTransaction);
            }

            logger.info("充值成功：钱包ID={}, 充值金额={}, 返点={}, 当前余额={}", 
                walletId, amount, bonus, wallet.getBalance());

            return rechargeTransaction;

        } catch (Exception e) {
            logger.error("充值失败：钱包ID={}, 金额={}, 错误={}", walletId, amount, e.getMessage());
            throw new RuntimeException("充值失败：" + e.getMessage(), e);
        }
    }

    @Override
    public VirtualWalletTransaction withdraw(Long walletId, BigDecimal amount, String remark) {
        try {
            // 1. 获取钱包
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            // 2. 计算提现手续费
            BigDecimal fee = calculateWithdrawFee(amount);
            
            // 3. 记录提现前余额
            BigDecimal balanceBefore = wallet.getBalance();

            // 4. 调用Domain对象的提现方法（充血模型）
            wallet.withdraw(amount, fee);

            // 5. 保存钱包状态
            virtualWalletRepository.save(wallet);

            // 6. 记录提现交易流水
            VirtualWalletTransaction withdrawTransaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount.add(fee))
                .transactionType(TransactionType.WITHDRAW)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .bonusOrFee(fee)
                .description("提现（含手续费" + fee + "元）")
                .remark(remark)
                .build();
            transactionRepository.save(withdrawTransaction);

            // 7. 如果有手续费，记录手续费交易
            if (fee.compareTo(BigDecimal.ZERO) > 0) {
                VirtualWalletTransaction feeTransaction = new VirtualWalletTransaction.Builder()
                    .walletId(walletId)
                    .amount(fee)
                    .transactionType(TransactionType.WITHDRAW_FEE)
                    .balanceBefore(balanceBefore)
                    .balanceAfter(wallet.getBalance())
                    .bonusOrFee(fee)
                    .description("提现手续费")
                    .remark("提现" + amount + "元，手续费" + fee + "元")
                    .build();
                transactionRepository.save(feeTransaction);
            }

            logger.info("提现成功：钱包ID={}, 提现金额={}, 手续费={}, 当前余额={}", 
                walletId, amount, fee, wallet.getBalance());

            return withdrawTransaction;

        } catch (Exception e) {
            logger.error("提现失败：钱包ID={}, 金额={}, 错误={}", walletId, amount, e.getMessage());
            throw new RuntimeException("提现失败：" + e.getMessage(), e);
        }
    }

    // ==================== 转账和支付 ====================

    @Override
    public boolean transfer(Long fromWalletId, Long toWalletId, BigDecimal amount, Long orderId, String remark) {
        try {
            // 1. 获取转出钱包
            VirtualWallet fromWallet = virtualWalletRepository.findById(fromWalletId)
                .orElseThrow(() -> new IllegalArgumentException("转出钱包不存在"));
            
            // 2. 获取转入钱包
            VirtualWallet toWallet = virtualWalletRepository.findById(toWalletId)
                .orElseThrow(() -> new IllegalArgumentException("转入钱包不存在"));

            // 3. 记录转账前余额
            BigDecimal fromBalanceBefore = fromWallet.getBalance();
            BigDecimal toBalanceBefore = toWallet.getBalance();

            // 4. 调用Domain对象的转账方法（充血模型）
            fromWallet.transfer(amount);  // 转出
            toWallet.receive(amount);      // 转入

            // 5. 保存钱包状态
            virtualWalletRepository.save(fromWallet);
            virtualWalletRepository.save(toWallet);

            // 6. 记录转出交易
            VirtualWalletTransaction outTransaction = new VirtualWalletTransaction.Builder()
                .walletId(fromWalletId)
                .amount(amount)
                .transactionType(TransactionType.TRANSFER_OUT)
                .fromWalletId(fromWalletId)
                .toWalletId(toWalletId)
                .orderId(orderId)
                .balanceBefore(fromBalanceBefore)
                .balanceAfter(fromWallet.getBalance())
                .description("转账给钱包" + toWalletId)
                .remark(remark)
                .build();
            transactionRepository.save(outTransaction);

            // 7. 记录转入交易
            VirtualWalletTransaction inTransaction = new VirtualWalletTransaction.Builder()
                .walletId(toWalletId)
                .amount(amount)
                .transactionType(TransactionType.TRANSFER_IN)
                .fromWalletId(fromWalletId)
                .toWalletId(toWalletId)
                .orderId(orderId)
                .balanceBefore(toBalanceBefore)
                .balanceAfter(toWallet.getBalance())
                .description("收到钱包" + fromWalletId + "的转账")
                .remark(remark)
                .build();
            transactionRepository.save(inTransaction);

            logger.info("转账成功：从钱包{}转账{}元到钱包{}", fromWalletId, amount, toWalletId);

            return true;

        } catch (Exception e) {
            logger.error("转账失败：从钱包{}到钱包{}, 金额={}, 错误={}", 
                fromWalletId, toWalletId, amount, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean payOrder(Long walletId, BigDecimal amount, Long orderId) {
        try {
            // 获取钱包
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal balanceBefore = wallet.getBalance();

            // 冻结资金
            wallet.freeze(amount);

            // 保存钱包状态
            virtualWalletRepository.save(wallet);

            // 记录冻结交易
            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.FREEZE)
                .orderId(orderId)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("订单支付，冻结资金")
                .remark("订单ID: " + orderId)
                .build();
            transactionRepository.save(transaction);

            logger.info("订单支付成功：钱包ID={}, 冻结金额={}, 订单ID={}", walletId, amount, orderId);

            return true;

        } catch (Exception e) {
            logger.error("订单支付失败：钱包ID={}, 金额={}, 订单ID={}, 错误={}", 
                walletId, amount, orderId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean confirmOrder(Long buyerWalletId, Long sellerWalletId, BigDecimal amount, Long orderId) {
        try {
            // 获取买家钱包
            VirtualWallet buyerWallet = virtualWalletRepository.findById(buyerWalletId)
                .orElseThrow(() -> new IllegalArgumentException("买家钱包不存在"));
            
            // 获取卖家钱包
            VirtualWallet sellerWallet = virtualWalletRepository.findById(sellerWalletId)
                .orElseThrow(() -> new IllegalArgumentException("卖家钱包不存在"));

            BigDecimal buyerBalanceBefore = buyerWallet.getBalance();
            BigDecimal buyerFrozenBefore = buyerWallet.getFrozenAmount();
            BigDecimal sellerBalanceBefore = sellerWallet.getBalance();

            // 扣除买家冻结资金
            buyerWallet.deductFrozen(amount);
            
            // 转给卖家
            sellerWallet.receive(amount);

            // 保存钱包状态
            virtualWalletRepository.save(buyerWallet);
            virtualWalletRepository.save(sellerWallet);

            // 记录买家交易
            VirtualWalletTransaction buyerTransaction = new VirtualWalletTransaction.Builder()
                .walletId(buyerWalletId)
                .amount(amount)
                .transactionType(TransactionType.TRANSFER_OUT)
                .fromWalletId(buyerWalletId)
                .toWalletId(sellerWalletId)
                .orderId(orderId)
                .balanceBefore(buyerBalanceBefore)
                .balanceAfter(buyerWallet.getBalance())
                .description("确认收货，支付给卖家")
                .remark("订单ID: " + orderId + ", 冻结金额从" + buyerFrozenBefore + "减至" + buyerWallet.getFrozenAmount())
                .build();
            transactionRepository.save(buyerTransaction);

            // 记录卖家交易
            VirtualWalletTransaction sellerTransaction = new VirtualWalletTransaction.Builder()
                .walletId(sellerWalletId)
                .amount(amount)
                .transactionType(TransactionType.TRANSFER_IN)
                .fromWalletId(buyerWalletId)
                .toWalletId(sellerWalletId)
                .orderId(orderId)
                .balanceBefore(sellerBalanceBefore)
                .balanceAfter(sellerWallet.getBalance())
                .description("买家确认收货，收到货款")
                .remark("订单ID: " + orderId)
                .build();
            transactionRepository.save(sellerTransaction);

            logger.info("确认订单成功：买家钱包={}, 卖家钱包={}, 金额={}, 订单ID={}", 
                buyerWalletId, sellerWalletId, amount, orderId);

            return true;

        } catch (Exception e) {
            logger.error("确认订单失败：买家钱包={}, 卖家钱包={}, 金额={}, 订单ID={}, 错误={}", 
                buyerWalletId, sellerWalletId, amount, orderId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean cancelOrder(Long walletId, BigDecimal amount, Long orderId) {
        try {
            // 获取钱包
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal balanceBefore = wallet.getBalance();
            BigDecimal frozenBefore = wallet.getFrozenAmount();

            // 解冻资金
            wallet.unfreeze(amount);

            // 保存钱包状态
            virtualWalletRepository.save(wallet);

            // 记录解冻交易
            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.UNFREEZE)
                .orderId(orderId)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("取消订单，解冻资金")
                .remark("订单ID: " + orderId + ", 冻结金额从" + frozenBefore + "减至" + wallet.getFrozenAmount())
                .build();
            transactionRepository.save(transaction);

            logger.info("取消订单成功：钱包ID={}, 解冻金额={}, 订单ID={}", walletId, amount, orderId);

            return true;

        } catch (Exception e) {
            logger.error("取消订单失败：钱包ID={}, 金额={}, 订单ID={}, 错误={}", 
                walletId, amount, orderId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean refund(Long sellerWalletId, Long buyerWalletId, BigDecimal amount, Long orderId) {
        try {
            // 获取卖家钱包
            VirtualWallet sellerWallet = virtualWalletRepository.findById(sellerWalletId)
                .orElseThrow(() -> new IllegalArgumentException("卖家钱包不存在"));
            
            // 获取买家钱包
            VirtualWallet buyerWallet = virtualWalletRepository.findById(buyerWalletId)
                .orElseThrow(() -> new IllegalArgumentException("买家钱包不存在"));

            BigDecimal sellerBalanceBefore = sellerWallet.getBalance();
            BigDecimal buyerBalanceBefore = buyerWallet.getBalance();

            // 卖家扣款
            sellerWallet.transfer(amount);
            
            // 买家收款
            buyerWallet.receive(amount);

            // 保存钱包状态
            virtualWalletRepository.save(sellerWallet);
            virtualWalletRepository.save(buyerWallet);

            // 记录卖家退款交易
            VirtualWalletTransaction sellerTransaction = new VirtualWalletTransaction.Builder()
                .walletId(sellerWalletId)
                .amount(amount)
                .transactionType(TransactionType.REFUND)
                .fromWalletId(sellerWalletId)
                .toWalletId(buyerWalletId)
                .orderId(orderId)
                .balanceBefore(sellerBalanceBefore)
                .balanceAfter(sellerWallet.getBalance())
                .description("退款给买家")
                .remark("订单ID: " + orderId)
                .build();
            transactionRepository.save(sellerTransaction);

            // 记录买家收款交易
            VirtualWalletTransaction buyerTransaction = new VirtualWalletTransaction.Builder()
                .walletId(buyerWalletId)
                .amount(amount)
                .transactionType(TransactionType.REFUND)
                .fromWalletId(sellerWalletId)
                .toWalletId(buyerWalletId)
                .orderId(orderId)
                .balanceBefore(buyerBalanceBefore)
                .balanceAfter(buyerWallet.getBalance())
                .description("收到卖家退款")
                .remark("订单ID: " + orderId)
                .build();
            transactionRepository.save(buyerTransaction);

            logger.info("退款成功：卖家钱包={}, 买家钱包={}, 金额={}, 订单ID={}", 
                sellerWalletId, buyerWalletId, amount, orderId);

            return true;

        } catch (Exception e) {
            logger.error("退款失败：卖家钱包={}, 买家钱包={}, 金额={}, 订单ID={}, 错误={}", 
                sellerWalletId, buyerWalletId, amount, orderId, e.getMessage());
            return false;
        }
    }

    // ==================== 冻结和解冻 ====================

    @Override
    public boolean freezeAmount(Long walletId, BigDecimal amount, String remark) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal balanceBefore = wallet.getBalance();

            wallet.freeze(amount);
            virtualWalletRepository.save(wallet);

            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.FREEZE)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("冻结资金")
                .remark(remark)
                .build();
            transactionRepository.save(transaction);

            return true;
        } catch (Exception e) {
            logger.error("冻结资金失败：钱包ID={}, 金额={}, 错误={}", walletId, amount, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean unfreezeAmount(Long walletId, BigDecimal amount, String remark) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal balanceBefore = wallet.getBalance();

            wallet.unfreeze(amount);
            virtualWalletRepository.save(wallet);

            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.UNFREEZE)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("解冻资金")
                .remark(remark)
                .build();
            transactionRepository.save(transaction);

            return true;
        } catch (Exception e) {
            logger.error("解冻资金失败：钱包ID={}, 金额={}, 错误={}", walletId, amount, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean freezeWallet(Long walletId) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            wallet.freezeWallet();
            virtualWalletRepository.save(wallet);

            logger.info("钱包冻结成功：钱包ID={}", walletId);
            return true;
        } catch (Exception e) {
            logger.error("钱包冻结失败：钱包ID={}, 错误={}", walletId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean unfreezeWallet(Long walletId) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            wallet.unfreezeWallet();
            virtualWalletRepository.save(wallet);

            logger.info("钱包解冻成功：钱包ID={}", walletId);
            return true;
        } catch (Exception e) {
            logger.error("钱包解冻失败：钱包ID={}, 错误={}", walletId, e.getMessage());
            return false;
        }
    }

    // ==================== VIP和透支管理 ====================

    @Override
    public boolean setVip(Long walletId, BigDecimal overdraftLimit) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            wallet.setAsVip(overdraftLimit);
            virtualWalletRepository.save(wallet);

            logger.info("设置VIP成功：钱包ID={}, 透支额度={}", walletId, overdraftLimit);
            return true;
        } catch (Exception e) {
            logger.error("设置VIP失败：钱包ID={}, 错误={}", walletId, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean cancelVip(Long walletId) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            if (wallet.getOverdraftUsed().compareTo(BigDecimal.ZERO) > 0) {
                throw new IllegalStateException("存在未还清的透支，无法取消VIP");
            }

            wallet.cancelVip();
            virtualWalletRepository.save(wallet);

            logger.info("取消VIP成功：钱包ID={}", walletId);
            return true;
        } catch (Exception e) {
            logger.error("取消VIP失败：钱包ID={}, 错误={}", walletId, e.getMessage());
            return false;
        }
    }

    @Override
    public VirtualWalletTransaction repay(Long walletId, BigDecimal amount) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal overdraftBefore = wallet.getOverdraftUsed();
            BigDecimal balanceBefore = wallet.getBalance();

            wallet.repay(amount);
            virtualWalletRepository.save(wallet);

            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(amount)
                .transactionType(TransactionType.REPAYMENT)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("还款")
                .remark("透支从" + overdraftBefore + "减至" + wallet.getOverdraftUsed())
                .build();
            transactionRepository.save(transaction);

            logger.info("还款成功：钱包ID={}, 还款金额={}, 剩余透支={}", 
                walletId, amount, wallet.getOverdraftUsed());

            return transaction;

        } catch (Exception e) {
            logger.error("还款失败：钱包ID={}, 金额={}, 错误={}", walletId, amount, e.getMessage());
            throw new RuntimeException("还款失败：" + e.getMessage(), e);
        }
    }

    @Override
    public BigDecimal calculateInterest(Long walletId) {
        VirtualWallet wallet = virtualWalletRepository.findById(walletId)
            .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));
        return wallet.calculateInterest();
    }

    @Override
    public VirtualWalletTransaction payInterest(Long walletId) {
        try {
            VirtualWallet wallet = virtualWalletRepository.findById(walletId)
                .orElseThrow(() -> new IllegalArgumentException("钱包不存在"));

            BigDecimal interest = wallet.calculateInterest();
            if (interest.compareTo(BigDecimal.ZERO) == 0) {
                throw new IllegalStateException("无需支付利息");
            }

            BigDecimal balanceBefore = wallet.getBalance();

            wallet.payInterest(interest);
            virtualWalletRepository.save(wallet);

            VirtualWalletTransaction transaction = new VirtualWalletTransaction.Builder()
                .walletId(walletId)
                .amount(interest)
                .transactionType(TransactionType.INTEREST)
                .balanceBefore(balanceBefore)
                .balanceAfter(wallet.getBalance())
                .description("支付透支利息")
                .remark("透支金额: " + wallet.getOverdraftUsed())
                .build();
            transactionRepository.save(transaction);

            logger.info("支付利息成功：钱包ID={}, 利息金额={}", walletId, interest);

            return transaction;

        } catch (Exception e) {
            logger.error("支付利息失败：钱包ID={}, 错误={}", walletId, e.getMessage());
            throw new RuntimeException("支付利息失败：" + e.getMessage(), e);
        }
    }

    // ==================== 交易记录查询 ====================

    @Override
    public List<VirtualWalletTransaction> getTransactionHistory(Long walletId) {
        return transactionRepository.findByWalletIdOrderByTransactionTimeDesc(walletId);
    }

    @Override
    public List<VirtualWalletTransaction> getTransactionsByOrderId(Long orderId) {
        return transactionRepository.findByOrderIdOrderByTransactionTimeDesc(orderId);
    }

    @Override
    public List<VirtualWalletTransaction> getTransactionsByType(Long walletId, String transactionType) {
        List<VirtualWalletTransaction> allTransactions = transactionRepository.findByWalletIdOrderByTransactionTimeDesc(walletId);
        return allTransactions.stream()
            .filter(t -> t.getTransactionType().equals(transactionType))
            .toList();
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 计算充值返点
     * @param amount 充值金额
     * @return 返点金额
     */
    private BigDecimal calculateRechargeBonus(BigDecimal amount) {
        List<WalletRule> rules = walletRuleRepository.findApplicableRules("RECHARGE", amount);
        if (rules.isEmpty()) {
            return BigDecimal.ZERO;
        }
        
        // 使用第一个匹配的规则（优先级最高）
        WalletRule rule = rules.get(0);
        return rule.calculateBonus(amount);
    }

    /**
     * 计算提现手续费
     * @param amount 提现金额
     * @return 手续费金额
     */
    private BigDecimal calculateWithdrawFee(BigDecimal amount) {
        List<WalletRule> rules = walletRuleRepository.findApplicableRules("WITHDRAW", amount);
        if (rules.isEmpty()) {
            return BigDecimal.ZERO;
        }
        
        // 使用第一个匹配的规则（优先级最高）
        WalletRule rule = rules.get(0);
        return rule.calculateBonus(amount);
    }
}
